package moro;

import java.io.File;

import javax.swing.filechooser.FileFilter;

/**
 * Gebruik strings om een filter te maken bij een JFileChooser.
 * @author J. Stellingwerf
 *
 */
public class ExtensionFileFilter extends FileFilter {
	String description;//Name of filter, i.e. "XML files"
	String extensions[];//Extensions to filter on
	
	/**
	 * Overload to second constructor
	 * @param description
	 * @param extension
	 */
	public ExtensionFileFilter(String description, String extension)
	{
		this(description, new String[] { extension});
	}
	
	/**
	 * Set the description and extensions to be filtered
	 * @param description
	 * @param extensions
	 */
	public ExtensionFileFilter(String description, String[] extensions)
	{
		if(description == null)//Null check description
		{
			this.description = extensions[0];
		}
		else
		{
			this.description = description;
		}
		
		this.extensions = extensions;
	}

	/**
	 * Return boolean whether file passed filter
	 */
	public boolean accept(File f) {
		if(f.isDirectory())
		{
			return true;//Browsing through directories is allowed
		}
		else
		{
			String path = f.getAbsolutePath().toLowerCase();//
			for(String extension:extensions)
			{
				if(path.endsWith(extension.toLowerCase()) && (path.charAt(path.length() - extension.length() -1) == '.'))
				{
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Return name of filter
	 */
	public String getDescription() {
		return description;
	}

}
